package com.itboye.lottery.retrofit;

import android.os.Looper;
import com.google.gson.Gson;
import com.itboye.lottery.alert.ByAlert;
import com.itboye.lottery.app.MyApplication;
import com.itboye.lottery.utils.Const;
import okhttp3.Response;
import okhttp3.ResponseBody;
import retrofit2.Converter;

import java.io.IOException;
import java.lang.reflect.Type;

import static com.itboye.lottery.utils.SPUtils.getSp;
import static com.itboye.lottery.utils.Utils.clip;

public class GsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {

    private final Gson gson;
    private final Type type;


    public GsonResponseBodyConverter(Gson gson, Type type) {
        this.gson = gson;
        this.type = type;
    }


    @Override
    public T convert(ResponseBody value) throws IOException {
        String response = value.string();
        //先将返回的json数据解析到Response中，如果code==200，则解析到我们的实体基类中，否则抛异常
        HttpResponse httpResult = gson.fromJson(response, HttpResponse.class);
        if (httpResult.getCode()==1999) {
            System.out.println(MyApplication.Companion.getInstance().getTopActivity()+">>>>顶部的 activity");
            Looper.prepare();
            clip(httpResult.getData()+"");
//            Looper.loop();
            MyApplication.Companion.getInstance().showUpdateVersionDialog("有新版本可更新,链接已复制到系统粘贴版，请前往浏览器粘贴下载"+httpResult.getData());
            //抛出异常 需要更新app
            throw new ApiException(httpResult.getCode(), "有新版本可更新，否则某些功能奖无法使用哦,链接已复制到系统粘贴版，请前往浏览器粘贴下载");
        }
        else if (httpResult.getCode() >= 0) {
            //200的时候就直接解析，不可能出现解析异常。因为我们实体基类中传入的泛型，就是数据成功时候的格式
            return gson.fromJson(response, type);
        } else {
//            ErrorResponse errorResponse = gson.fromJson(response, ErrorResponse.class);
//            //抛一个自定义ResultException 传入失败时候的状态码，和信息
            throw new ApiException(httpResult.getCode(), httpResult.getMsg());
        }
    }
}
